package com.styytech.dadabao.ui.my.accountset;


import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.lidroid.xutils.view.annotation.ContentView;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.loopj.android.http.RequestParams;
import com.styytech.dadabao.DadaApplication;
import com.styytech.dadabao.R;
import com.styytech.dadabao.api.requestresult.RegistResult;
import com.styytech.dadabao.api.response.AbstractResponseResult;
import com.styytech.dadabao.api.templates.HttpRequest;
import com.styytech.dadabao.base.BaseActivity;
import com.styytech.dadabao.constant.ConstantsServerUrl;
import com.styytech.dadabao.exception.ArgumentsException;
import com.styytech.dadabao.exception.RequestException;
import com.styytech.dadabao.utils.CommonUtils;
import com.styytech.dadabao.utils.Md5Utils;
import com.styytech.dadabao.utils.SpUser;
import com.styytech.dadabao.widge.dialog.CustomLoadingDialog;

/**
 * 设置支付密码
 */
@ContentView(R.layout.activity_paypassword_set)
public class PayforSetActivity extends BaseActivity {
    /**
     * 验证码
     */
    public final int REQUEST_CODE_AUTH_CODE = 1;
    /**
     * 确认设置支付密码
     */
    public final int REQUEST_CODE_SUBMIT = 2;
    /**
     * 确认修改支付密码
     */
    public final int REQUEST_CODE_UPDATE = 3;

    /*设置支付密码整体布局*/
    @ViewInject(R.id.llyt_set_payfor)
    LinearLayout llyt_set_payfor;
    /*获取验证码*/
    @ViewInject(R.id.tv_auth_code)
    TextView tv_auth_code;
    /*验证码*/
    @ViewInject(R.id.et_auth_code)
    EditText et_auth_code;
    /*设置支付密码*/
    @ViewInject(R.id.et_set_payfor)
    EditText et_set_payfor;
    /*确认支付密码*/
    @ViewInject(R.id.et_confirm_payfor)
    EditText et_confirm_payfor;
    /*确认修改*/
    @ViewInject(R.id.bt_ok)
    Button bt_ok;
    /*修改支付密码整体布局*/
    @ViewInject(R.id.llyt_update_payfor)
    LinearLayout llyt_update_payfor;

    /*原支付密码*/
    @ViewInject(R.id.et_payfor_old)
    EditText et_payfor_old;
    /*新支付密码*/
    @ViewInject(R.id.et_payfor_new)
    EditText et_payfor_new;
    /*确认支付密码*/
    @ViewInject(R.id.et_payfor_confirm)
    EditText et_payfor_confirm;


    /*上下文*/
    private Context mContext;
    /*loading框*/
    CustomLoadingDialog mdlg;
    private String phoneNum = "";// 手机号
    private String auchuCode = "";// 验证码
    private String password = "";// 密码
    private String passwordOk = "";// 确认密码
    private int payforView = 0;//0:设置支付密码界面，1：修改支付密码界面

    /**
     * 计时器
     */
    private TimeCount timeCount = null;
    /**
     * 0：还未计时
     * 1：正在计时：
     * -1：
     */
    private boolean isTimeCount = false;// false：还未计时或计时结束，true：正在计时

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = this;
        initView();
        initData();
    }

    /**
     * 初始化视图
     */
    private void initView() {
        DadaApplication.addActivity(this);
        setTopBar("设置支付密码", View.VISIBLE);

    }

    /**
     * 初始界面设置
     */
    private void initData() {
        payforView = SpUser.getBuyPasswordStatus(mContext);
        if (payforView == 1) {// 已设置过支付密码，则显示修改支付密码界面
            setTopBar("修改支付密码", View.VISIBLE);
            llyt_update_payfor.setVisibility(View.VISIBLE);
            llyt_set_payfor.setVisibility(View.GONE);
            bt_ok.setText("确认修改");
        } else {// 显示设置支付密码界面
            llyt_update_payfor.setVisibility(View.GONE);
            llyt_set_payfor.setVisibility(View.VISIBLE);
        }
    }

    @OnClick({R.id.bt_ok, R.id.tv_auth_code})
    public void click(View view) {
        switch (view.getId()) {
            case R.id.tv_auth_code:// 获取验证码
                getAuthCode();
                break;
            case R.id.bt_ok:// 确认修改
                if (payforView == 1) {//如果是修改界面，则执行修改支付密码请求
                    submitUpdatePayfor();
                } else {//如果是设置界面，则执行设置支付密码请求
                    submitSetPayfor();
                }
                break;
        }
    }

    /**
     * 获取验证码
     */
    public void getAuthCode() {
        /*获取用户输入的手机号*/
        phoneNum = SpUser.getUserName(mContext);
        /*手机号过滤*/
        if (phoneNum.isEmpty()) {
            //手机号码不能为空
            toast(getResources().getString(R.string.number_no_empty));
            return;
        } else if (phoneNum.length() != 11) {
            //请填写正确手机号码
            toast(getResources().getString(R.string.number_to_right));
            return;
        }
        /*如果未开始计时或者计时结束，才能再次获取验证码*/
        if (!isTimeCount) { // 发送
            // 显示对话框
            mdlg = CommonUtils.getCustomLoadingDialog(context, mdlg, "获取验证码", true);
            mdlg.show();
            /*获取验证码的接口*/
            String url = ConstantsServerUrl.getCheckCode();
            /*设置参数*/
            RequestParams params = new RequestParams();
            params.put("mobileNumber", phoneNum);
            /*验证码请求*/
            requestAuthCode(REQUEST_CODE_AUTH_CODE, url, params);
        } else {
            //短信已发送
            CommonUtils.showToastMsg(context, "" + getResources().getString(R.string.sms_had_sent));
        }
    }


    /**
     * 提交设置支付密码
     */
    public void submitSetPayfor() {
        /*获取手机号*/
        phoneNum = SpUser.getUserName(mContext);
        auchuCode = et_auth_code.getText().toString().trim();
        password = et_set_payfor.getText().toString().trim();
        passwordOk = et_confirm_payfor.getText().toString().trim();
        /*对验证码异常过滤*/
        if (auchuCode.isEmpty()) {
            //验证码不能为空
            toast(getResources().getString(R.string.code_no_empty));
            return;
        } else if (auchuCode.length() != 6) {
            //验证码长度为6位
            toast(getResources().getString(R.string.code_must_six));
            return;
        } else if (password.isEmpty()) {
            //密码不能为空
            toast(getResources().getString(R.string.pwd_no_empty));
            return;
        } else if (password.length() < 6) {
            //密码不能少于6位
            toast(getResources().getString(R.string.pwd_too_low));
            return;
        } else if (password.length() > 30) {
            //密码长度不能大于30位
            toast(getResources().getString(R.string.pwd_too_much));
            return;
        } else if (passwordOk.isEmpty()) {
            //确认密码不能为空
            toast(getResources().getString(R.string.pwd_ensure_no_empty));
            return;
        } else if (!password.equals(passwordOk)) {
            //两次密码不一致
            toast(getResources().getString(R.string.pwd_no_agree));
            return;
        }

        // 显示对话框
        mdlg = CommonUtils.getCustomLoadingDialog(context, mdlg, "设置支付密码", true);
        mdlg.show();

        /*获取设置支付密码请求接口*/
        String url = ConstantsServerUrl.getSaveUserPayPasswordUrl();
        /*设置参数*/
        RequestParams params = new RequestParams();
        params.put("mobile", phoneNum);
        params.put("checkCode", auchuCode);
        params.put("payPassword", Md5Utils.hash(password));
        params.put("token", SpUser.getUserToken(mContext));
        /*请求校验验证码*/
        requestAuthCode(REQUEST_CODE_SUBMIT, url, params);
    }

    /**
     * 提交修改支付密码
     * payPassword
     * oldPayPassword
     * token
     */
    public void submitUpdatePayfor() {
        String oldPayPassword = et_payfor_old.getText().toString().trim();
        password = et_payfor_new.getText().toString().trim();
        passwordOk = et_payfor_confirm.getText().toString().trim();
        /*简单的条件过滤*/
        if (oldPayPassword.isEmpty()) {
            //密码不能为空
            toast(getResources().getString(R.string.pwd_no_empty_old));
            return;
        } else if (oldPayPassword.length() < 6) {
            //密码不能少于6位
            toast(getResources().getString(R.string.pwd_too_low_old));
            return;
        } else if (password.isEmpty()) {
            //密码不能为空
            toast(getResources().getString(R.string.pwd_no_empty_new));
            return;
        } else if (password.length() < 6) {
            //密码不能少于6位
            toast(getResources().getString(R.string.pwd_too_low_new));
            return;
        } else if (password.length() > 30) {
            //密码长度不能大于30位
            toast(getResources().getString(R.string.pwd_too_much));
            return;
        } else if (passwordOk.isEmpty()) {
            //确认密码不能为空
            toast(getResources().getString(R.string.pwd_ensure_no_empty));
            return;
        } else if (!password.equals(passwordOk)) {
            //两次密码不一致
            toast(getResources().getString(R.string.pwd_no_agree));
            return;
        }

        // 显示对话框
        mdlg = CommonUtils.getCustomLoadingDialog(context, mdlg, "修改支付密码", true);
        mdlg.show();

        /*获取修改支付密码请求接口*/
        String url = ConstantsServerUrl.getUpdateUserPayPasswordUrl();
        /*设置参数*/
        RequestParams params = new RequestParams();
        params.put("oldPayPassword", Md5Utils.hash(oldPayPassword));
        params.put("payPassword", Md5Utils.hash(password));
        params.put("token", SpUser.getUserToken(mContext));
        /*请求校验验证码*/
        requestAuthCode(REQUEST_CODE_UPDATE, url, params);
    }

    /**
     * 请求校验验证码
     *
     * @param rquestCode 请求码
     * @param url        请求的url接口
     * @param params     请求的参数
     */
    public void requestAuthCode(int rquestCode, String url, RequestParams params) {

        //获取验证码
        RegistResult requestResult = new RegistResult(rquestCode, responseResult);
        try {
            new HttpRequest(this).doPost(requestResult, url, params);
        } catch (ArgumentsException e) {
            Log.i("INFO", "1e:" + e);
            e.printStackTrace();
        } catch (RequestException e) {
            Log.i("INFO", "2e:" + e);
            e.printStackTrace();
        }
    }


    /**
     * 注册请求结果处理
     */
    AbstractResponseResult responseResult = new AbstractResponseResult() {

        @Override
        public void executeSuccess(Object object) {
            CommonUtils.closeDialog(mdlg);
            switch ((int) object) {
                case REQUEST_CODE_AUTH_CODE:
                    //获取验证码成功之后
                     /*开始计时*/
                    timeCount = new TimeCount(60000, 1000);
                    timeCount.start();
                    break;
                case REQUEST_CODE_SUBMIT://提交设置的密码成功后
                    SpUser.setBuyPasswordStatus(mContext, 1);
                    CommonUtils.closeDialog(mdlg);
                    toast("设置支付密码成功");
                    finish();
                    break;
                case REQUEST_CODE_UPDATE://提交修改的密码成功后
                    CommonUtils.closeDialog(mdlg);
                    toast("修改支付密码成功");
                    finish();
                    break;
            }

        }

        @Override
        public void executeError(String message, int errorCode) {
            CommonUtils.showToastMsg(context, "" + message);
            CommonUtils.closeDialog(mdlg);
        }

        @Override
        public void HttpError(String message, int errorCode) {
            CommonUtils.closeDialog(mdlg);
            CommonUtils.showToastMsg(context, "" + message);
        }
    };

    /**
     * 倒计时
     */
    class TimeCount extends CountDownTimer {
        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);//参数依次为总时长,和计时的时间间隔
        }

        /**
         * 计时完毕时触发
         */
        @Override
        public void onFinish() {
            isTimeCount = false;
            tv_auth_code.setText("重新发送");
            tv_auth_code.setClickable(true);
            tv_auth_code.setTextColor(getResources().getColor(R.color.main_red));
        }

        /**
         * 计时过程显示
         *
         * @param millisUntilFinished
         */
        @Override
        public void onTick(long millisUntilFinished) {
            isTimeCount = true;
            tv_auth_code.setClickable(false);
            tv_auth_code.setTextColor(getResources().getColor(R.color.gray));
            tv_auth_code.setText(millisUntilFinished / 1000 + "秒后重试");
        }
    }

    /**
     * 启动界面
     *
     * @param cls 需要启动的界面类
     */
    private void startNextActivity(Class<?> cls) {
        Intent intent = new Intent(mContext, cls);
        startActivity(intent);
    }

    /**
     * 提示消息
     *
     * @param str 需要提示的消息
     */
    private void toast(String str) {
        Toast.makeText(mContext, str, Toast.LENGTH_SHORT).show();
    }

}

